package cn.pedant.checkup;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;


import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.pedant.SweetAlert.R;
import cn.pedant.SweetAlert.SweetAlertDialog;


/**
 * Created by admin on 2015/10/22.
 */
public class CheckUpdate {
    private String localVersion;//获取本地版本号
    private final int UPDATA_NONEED = 0;//不需要更新
    private final int UPDATA_CLIENT = 1;//通知用户更新
    private final int GET_UNDATAINFO_ERROR = 2;//获取信息出错
    private final int SDCARD_NOMOUNTED = 3;
    private final int DOWN_ERROR = 4;//下载出错
    private UpdataInfo info;
    Context context;
    SharedPreferences remeber;
    String path = null;
    boolean isAuto = false;
    private SweetAlertDialog checkup;
    public CheckUpdate(Context context) {
        this.context = context;
        remeber = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
    }

    /***
     * 获取包名
     */
    private String getVersionName() throws Exception {
        //getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageManager packageManager = context.getPackageManager();

        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(),
                0);
//        Log.e("package", "版本名"+packInfo.versionName);
        return packInfo.versionName;
    }

    public void checkUpAuto(String url) {
        try {
            isAuto = true;
            this.path = url;
            localVersion = getVersionName();
            CheckVersionTask cv = new CheckVersionTask();
            new Thread(cv).start();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void checkUp(String url) {
           checkup= new SweetAlertDialog(context,SweetAlertDialog.PROGRESS_TYPE);
            checkup.setTitleText("检查更新……");
            checkup.setCanceledOnTouchOutside(false);
            checkup.show();
        try {
            isAuto = false;
            this.path = url;
            localVersion = getVersionName();
            CheckVersionTask cv = new CheckVersionTask();
            new Thread(cv).start();


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public class CheckVersionTask implements Runnable {
        InputStream is;

        public void run() {
            try {

//                Log.e("aaa", "111");
                URL url = new URL(path);
//                Log.e("aaa","222");
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
//                Log.e("aaa","333");
                conn.setConnectTimeout(5000);
//                Log.e("aaa","444");
                conn.setRequestMethod("GET");
//                Log.e("aaa","555");
                int responseCode = conn.getResponseCode();
//                Log.e("responseCode",responseCode+"");
                if (responseCode == 200) {
                    // 从服务器获得一个输入流
                    is = conn.getInputStream();
                }
//                Log.e("is",is+"");
                info = UpdataInfoParser.getUpdataInfo(is);
//                Log.e("info",info+"");
                if (info.getVersion().equals(localVersion)) {
//                    Log.i(TAG, "版本号相同" + info.getVersion());
                    Message msg = new Message();
                    msg.what = UPDATA_NONEED;
                    handlerupdate.sendMessage(msg);
                    // LoginMain();
                } else {
//                    Log.i(TAG, "版本号不相同 "+info.getVersion());
                    Message msg = new Message();
                    msg.what = UPDATA_CLIENT;
                    handlerupdate.sendMessage(msg);
                }
            } catch (Exception e) {
                Message msg = new Message();
                msg.what = GET_UNDATAINFO_ERROR;
                handlerupdate.sendMessage(msg);
                e.printStackTrace();
            }
        }
    }

  private void   dissMissCheckUp(){
      if (!isAuto)
        if(checkup!=null){
            if (checkup.isShowing()){
                checkup.dismiss();
            }
        }
    }


    Handler handlerupdate = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {

                case UPDATA_NONEED:
                    dissMissCheckUp();
                    if (!isAuto) {
                        new SweetAlertDialog(context)
                                .setTitleText("不需要更新")
                                .show();
                    }
                    break;
                case UPDATA_CLIENT:
                    //对话框通知用户升级程序
                    dissMissCheckUp();
                    if (isAuto){
                        if (remeber.contains("date")) {
                            if (!remeber.getString("date", null).equals(getStringDateShort())) {
                                showUpdataDialog();
                            }
                        } else if (remeber.contains("verno")) {
                            if (!remeber.getString("verno", null).equals(info.getVersion())) {
                                showUpdataDialog();
                            }
                        } else {
                            showUpdataDialog();
                        }
                    }else {
                        showUpdataNowDialog();
                    }
                    Log.e("ver==", localVersion);
                    break;
                case GET_UNDATAINFO_ERROR:
                    //服务器超时
                    dissMissCheckUp();
                    if (!isAuto) {
                        new SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("获取服务器更新信息失败")
                                .show();
                    }
                    break;
                case DOWN_ERROR:
                    //下载apk失败
                    dissMissCheckUp();
                    new SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("下载新版本失败")
                            .show();
                    break;
            }
        }
    };

    private void showUpdataNowDialog(){
        new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE)
                .setTitleText("检测到有版本需要升级吗？")
                .setConfirmText("确定")
                .setCancelText("取消")
                .setCustomImage(R.drawable.ic_launcher)
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        Log.i("TAG下载更新", "下载apk,更新");
                        downLoadApk();
                        sweetAlertDialog.dismissWithAnimation();
                    }
                }).setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
            }
        })
                .showCancelButton(true)
                .show();

    }



    /*
     *
	 * 弹出对话框通知用户更新程序
	 *
	 * 弹出对话框的步骤：
	 *  1.创建alertDialog的builder.
	 *  2.要给builder设置属性, 对话框的内容,样式,按钮
	 *  3.通过builder 创建一个对话框
	 *  4.对话框show()出来
	 */
    protected void showUpdataDialog() {
        final boolean[] ischecked = {false};
        SweetAlertDialog sad = new SweetAlertDialog(context, SweetAlertDialog.HWZ_CHECKUP);
        sad.setVerNo(info.getVersion());
        sad.setVerSize(info.getVersionsize());
        sad.setUpdateContent(info.getDescription());
        sad.setConfirmText("立即更新");
        if (!TextUtils.isEmpty(info.getIsforce())){
            if (info.getIsforce().equals("1")) {
                sad.setCancelText("稍后提醒");
            } else {
                sad.setCancelable(false);
            }
        }else {
            sad.setCancelable(false);
        }

        sad.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                Log.i("TAG下载更新", "下载apk,更新");
                downLoadApk();
                sweetAlertDialog.dismissWithAnimation();
            }
        }).setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                remeber.edit().clear().commit();
                Log.e("CGEC11111111======", ischecked[0] + "");
                if (ischecked[0]) {
                    remeber.edit().putString("verno", info.getVersion()).commit();
                } else {
                    remeber.edit().putString("date", getStringDateShort()).commit();
                }

                sweetAlertDialog.dismiss();
            }
        })
                .setmChangeListener(new SweetAlertDialog.OnSweetChangeListener() {
                    @Override
                    public void onChecked(boolean isChecked) {
                        ischecked[0] = isChecked;
                        Log.e("CGEC======", ischecked[0] + "");
                    }
                })
                .showCancelButton(true)
                .show();

    }

    /**
     * 获取现在时间
     *
     * @return 返回短时间字符串格式yyyy-MM-dd
     */
    public static String getStringDateShort() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /*
     * 从服务器中下载APK
     */
    protected void downLoadApk() {
        View view = View.inflate(context, R.layout.updata_dialog, null);
        final AlertDialog alertDialog = new AlertDialog.Builder(context)
                .setView(view).create();
        alertDialog.setCanceledOnTouchOutside(false);//使除了dialog以外的地方不能被点击
        alertDialog.show();
        final RoundProgressBar progressBar = (RoundProgressBar) view.findViewById(R.id.roundProgressBar);
        Button button = (Button) view.findViewById(R.id.btn_sev);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = DownLoadManager.getFileFromServer(info.getUrl(), progressBar, context);
                    sleep(3000);
                    installApk(file);
                    alertDialog.dismiss();
                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = DOWN_ERROR;
                    handlerupdate.sendMessage(msg);
                    e.printStackTrace();
                }
            }
        }.start();
    }

    //安装apk
    protected void installApk(File file) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }
}
